<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>测试</button>
    <script>
        var timer = setInterval(() => {
            console.log('1');
        }, 1000)
        clearInterval(timer)
        var btn = document.querySelector('button')
        btn.flag = true
        btn.onclick = function () {
            console.log(btn.flag);
            if (btn.flag) {
                console.log('开启定时器');
                timer = setInterval(() => {
                    console.log('1');
                }, 1000)
            }else{
                console.log("关闭定时器");
                clearInterval(timer)
            }
            btn.flag = !btn.flag
        }
    </script>
</body>

</html>